<template>
  <el-dialog
    v-model="visible"
    :title="titleMap[detailsType]"
    :width="detailsType < 4 ? '600px' : '450px'"
    :before-close="handleCancel"
  >
    <div v-if="detailsType" class="text-333333 text-14" :class="detailsType < 3 ? 'pl-30' : ''">
      <div v-if="detailsType < 3" class="mb-20">
        为了保证安全性，查看或重置client_sercret需要经过店铺创建者的手机号校验
      </div>
      <div v-if="detailsType < 3" class="flex mb-20 ml-26 gap-10">
        <span>手机号</span>
        <span>{{ userInfo.lecturerPhone }}</span>
      </div>
      <div v-if="detailsType == 3" class="mb-20">
        <div class="flex text-14">
          <div class="mr-24">IP白名单</div>
          <div class="text-cccccc">
            在IP白名单内的IP地址作为来源，获取access_token接口才可调用成功。
          </div>
        </div>
      </div>
      <el-form
        ref="postFormRef"
        :model="postForm"
        :rules="postFormRules"
        :label-width="detailsType < 4 ? '80px' : '120px'"
      >
        <el-form-item v-if="detailsType < 3" prop="captcha" class="relative">
          <el-input
            v-model="postForm.captcha"
            size="large"
            name="captcha"
            type="text"
            maxlength="14"
            placeholder="请输入验证码"
          />
          <img
            v-show="captchaImg"
            :src="captchaImg"
            class="absolute w-120 h-32 bottom-4 right-15 text-center cursor-pointer"
            title="点击图片重新获取验证码"
            @click="loadCaptcha"
          />
        </el-form-item>
        <el-form-item
          v-if="detailsType <= 3"
          :label="detailsType < 3 ? '验证码' : ''"
          :prop="detailsType < 3 ? 'code' : 'ip'"
        >
          <el-input
            v-if="detailsType < 3"
            v-model="postForm.code"
            size="large"
            placeholder="请输入验证码"
            maxlength="14"
          />
          <el-input
            v-if="detailsType == 3"
            v-model="postForm.ip"
            size="large"
            placeholder="请输入ip地址"
          />
          <el-button
            v-if="detailsType < 3"
            :disabled="postForm.captcha.length < 4 || isClick"
            class="cursor-pointer absolute w-100 h-20 bottom-4 right-15 text-center"
            text
            @click="getCheckCode"
          >
            {{ yzText }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="detailsType == 4" label="消息签名" prop="msgSign">
          <el-input v-model="postForm.msgSign" placeholder="请输入消息签名" />
        </el-form-item>

        <el-form-item v-if="detailsType == 4" label="消息接收URL" prop="msgUrl">
          <el-input v-model="postForm.msgUrl" placeholder="请输入消息URL" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useUserStore, useUserStoreHook } from "@/store";
import { UserInfo } from "@/api/system/user";
import { FormInstance, FormRules } from "element-plus";
import AuthAPI from "@/api/auth";
import { DashboardDialogFormData } from "@/api/dashboard";
import DashboardAPI from "@/api/dashboard";
// 用户状态管理器
const userStore = useUserStore();
// 获取用户信息
let userInfo: UserInfo = userStore.userInfo;
// 定义 props
const props = defineProps({
  // 是否展示详情弹出框
  modelValue: {
    type: Boolean,
    default: false,
  },
  // 宽度
  width: {
    type: String,
    default: "50%",
  },
  // 详情
  detailsParam: {
    type: Object,
    default: {},
  },
  // 详情类型 1：查看client_sercret  2：重置client_sercret  3：IP白名单  4：设置消息校验token  5：设置消息加密key  6：设置消息接受URL
  detailsType: {
    type: Number,
    default: 1,
  },
});
// 标题名称
const titleMap: Record<number, string> = {
  1: "查看client_sercret",
  2: "重置client_sercret",
  3: "IP白名单",
  4: "设置",
  5: "设置",
  6: "设置",
};
// 验证码图片
const captchaImg = ref<string>("");
// 表单Ref
const postFormRef = ref<FormInstance>();
// 表单数据
const postForm = ref<DashboardDialogFormData>({
  mobile: "",
  captcha: "",
  captchaKey: "",
  code: "",
  ip: "",
  msgSign: "",
  msgUrl: "",
});
// 表单规则
const postFormRules = ref<FormRules<DashboardDialogFormData>>({
  ip: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入IP地址"));
        } else if (
          !/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/.test(value)
        ) {
          callback(new Error("请输入正确的IP地址"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  msgSign: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入消息签名"));
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  msgUrl: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入消息url"));
        }
        if (
          !/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
            value
          )
        ) {
          callback("请输入正确的url地址");
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  captcha: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
// 防止多次点击
const isClick = ref<boolean>(false);
// 倒计时定时器
const interval = ref<NodeJS.Timeout | null>(null);
// 验证码倒计时
const yzText = ref<string>("获取验证码");
// 是否开启验证码
const isYz = ref<boolean>(false);
// 倒计时时间
const num = ref<number>(60);
// 防止多次点击
const btnLoading = ref<boolean>(false);
// 获取验证码
const loadCaptcha = () => {
  if (![1, 2].includes(props.detailsType)) return;
  AuthAPI.getCaptcha().then((data) => {
    postForm.value.captchaKey = data.key;
    captchaImg.value = data.img;
  });
};
// 获取验证码
const getCheckCode = () => {
  clearInterval(interval.value!);
  if (isClick.value) return;
  isClick.value = true;
  yzText.value = "正在发送短信";
  DashboardAPI.sendCodeByApp(postForm.value)
    .then(() => {
      getYzMethod();
      interval.value = setInterval(getYzMethod, 1000);
      ElMessage.success("验证码发送成功");
    })
    .catch(() => {
      isClick.value = false;
      yzText.value = "获取验证码";
      loadCaptcha();
    });
};
// 验证码倒计时
const getYzMethod = () => {
  isClick.value = true;
  isYz.value = false;
  num.value -= 1;
  yzText.value = num.value + "秒后重新获取";
  if (num.value === 0) {
    clearInterval(interval.value!);
    yzText.value = "获取验证码";
    num.value = 30;
    isClick.value = false;
    isYz.value = true;
  }
};
// 定义 emits
const emit = defineEmits(["update:modelValue", "confirm", "cancel", "resetUserInfo"]);
// 计算属性：用于双向绑定
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});
// 点击确认按钮
const handleConfirm = () => {
  // 验证表单参数是否正确
  postFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (btnLoading.value) return;
      btnLoading.value = true;
      if (props.detailsType == 1) {
        getAppSecret();
      } else if (props.detailsType == 2) {
        resetAppSecret();
      } else if (props.detailsType == 3) {
        addIpAddress();
      } else {
        setAppMsgReceive();
      }
    } else {
      loadCaptcha();
      btnLoading.value = false;
    }
  });
};
// 获取密钥
const getAppSecret = () => {
  DashboardAPI.getAppSecret(postForm.value)
    .then(async (res) => {
      btnLoading.value = false;
      userInfo.clientSecret = res.secret;
      ElMessage.success("查看成功!");
      emit("confirm");
      visible.value = false;
    })
    .catch(() => {
      loadCaptcha();
      btnLoading.value = false;
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
// 重置密钥
const resetAppSecret = () => {
  DashboardAPI.resetAppSecret(postForm.value)
    .then(async (res) => {
      emit("confirm");
      visible.value = false;
      getUserInfo("重置成功!");
    })
    .catch(() => {
      loadCaptcha();
      btnLoading.value = false;
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
// 添加IP白名单
const addIpAddress = () => {
  DashboardAPI.addIpAddress(postForm.value)
    .then(async (res) => {
      emit("confirm");
      visible.value = false;
      btnLoading.value = false;
      getUserInfo("添加ip成功!");
    })
    .catch(() => {
      btnLoading.value = false;
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
// 设置
const setAppMsgReceive = () => {
  DashboardAPI.setAppMsgReceive(postForm.value)
    .then(async (res) => {
      emit("confirm");
      visible.value = false;
      btnLoading.value = false;
      getUserInfo("设置成功!");
    })
    .catch(() => {
      btnLoading.value = false;
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
// 点击取消按钮
const handleCancel = () => {
  emit("cancel");
  visible.value = false;
};
// 获取用户信息
const getUserInfo = (tips: string) => {
  userStore.getUserInfo().then((data) => {
    userInfo = data;
    postForm.value.mobile = data.lecturerPhone;
    emit("resetUserInfo", data);
    ElMessage.success(tips);
  });
};
onMounted(() => {
  loadCaptcha();
});
</script>

<style scoped lang="scss"></style>
